package com.mccken.designpattern.proxy.proxy3;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import com.mccken.designpattern.proxy.support.MetricsCollector;
import com.mccken.designpattern.proxy.support.RequestInfo;

/**
 * @program: mccken-collect
 * @description:
 * @author: mccken
 * @create: 2022-10-26 20:25
 **/
public class DynamicProxyHandler implements InvocationHandler {

	private Object proxiedObject;
	private MetricsCollector metricsCollector = new MetricsCollector();
	
	public DynamicProxyHandler(Object proxiedObject) {
		this.proxiedObject = proxiedObject;
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		long startTimeStamp = System.currentTimeMillis();
		
		Object result = method.invoke(proxiedObject, args);
		
		long endTimeStamp = System.currentTimeMillis();
		long responseTime = startTimeStamp - endTimeStamp;
		String apiName = proxiedObject.getClass().getName() + "." + method.getName();
		RequestInfo requestInfo = new RequestInfo(apiName, responseTime, startTimeStamp);
		metricsCollector.recordRequest(requestInfo);
		return result;
	}
	
	
}
